<template>
  <van-button
    :icon="value ? 'star' : 'star-o'"
    :class="{
      collected: value
    }"
    :loading="loading"
    @click="onCollect"
  />
</template>

<script>
//将article/index.vue中的此行剪切过来
// 关注的模板，其实就是俩按钮：关注，已关注
import { addCollect, deleteCollect } from '@/api/article'

export default {
  name: 'CollectArticle',
  components: {},

  props: {
    value: {
      type: Boolean,
      required: true
    },

    articleId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      loading: false
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    //将article/index.vue中的这个方法剪切过来，然后修改为如下
    async onCollect() {
      // 开始请求

      this.loading = true
      try {
        // 是否收藏
        if (this.value) {
          // 父组件 传递articleId
          await deleteCollect(this.articleId)
        } else {
          await addCollect(this.articleId)
        }
        // 更新视图
        this.$emit('input', !this.value)
        // 自定义事件修改数据并不是立即的，所以这里也是!this.value
        this.$toast.success(!this.value ? '收藏成功' : '取消收藏')
      } catch (err) {
        console.log(err)
        this.$toast.fail('操作失败，请重试')
      }
      // 请求结束
      this.loading = false
    }
  }
}
</script>

<style scoped lang="less">
.collected {
  /deep/ .van-icon {
    color: #ffa500;
  }
}
</style>
